package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.dtos.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    /**
     * 自动补全功能，关键字联想功能，使用es
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        try {
            //2.创建SearchRequest并且指定索引名称
            SearchRequest searchRequest=new SearchRequest("app_info_article");

            //3. 执行DSL,实现自动补全
            searchRequest.source().suggest(new SuggestBuilder()
                    /**
                     * addSuggestion(String name, SuggestionBuilder<?> suggestion)
                     * 添加自动补全api
                     * 参数1表示指定自动补全操作的自定义名称
                     * 参数2表示执行自动补全构建
                     */
                            .addSuggestion("mySuggestion",
                                    SuggestBuilders.completionSuggestion("suggestion")//自动补全的字段是哪个
                                            .prefix(dto.getSearchWords())//表示以我们的搜索关键字作为前缀
                            .skipDuplicates(true)//表示如果有重复的，则覆盖
                            .size(dto.getPageSize())//表示自动补全的数量
                            )
            );
            //1.执行search方法
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //4.执行数据结果封装
            List list=new ArrayList();


            Suggest suggest = response.getSuggest();
            CompletionSuggestion mySuggestion = suggest.getSuggestion("mySuggestion");
            //获取自定义的补全字段下的所有的元素
            List<CompletionSuggestion.Entry.Option> options = mySuggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                //表示获取每一行的自动补全的元素字符串
                String value = option.getText().toString();
                list.add(value);
            }

            return ResponseResult.okResult(list);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"自动补全查询出现错误了");
        }
    }
}
